package com.authine.cloudpivot.ext.controller;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.AttachmentModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizCommentModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.type.ActionType;
import com.authine.cloudpivot.engine.enums.type.UnitType;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.helper.WorkflowInstanceOptions;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/instructor")
public class InstructorReviewController extends BaseController {

    @PersistenceContext
    EntityManager entityManager;


    @PostMapping("/performaudit")
    public ResponseResult newperformAudit(@RequestBody List<Map<String, String>> map) {
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        for (Map<String, String> m : map) {
            String objId = m.get("objId");
            BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("jssb", objId);
            String sbjb = bizObject.getString("sbjb");
            //职业发展等级  15 12  9
            String zyfzdj = bizObject.getString("zyfzdj");
            //职业等级  普通员工   主管
            String zydj = bizObject.getString("zydj");
            //中断时间
            String zdsj = bizObject.getString("zdsj");
            //参加工作时间
            Date cjgzsj = (Date) bizObject.get("cjgzsj");
            //专业技术职务  "初级", "中级", "副高", "高级"
            String zyzyzg = bizObject.getString("zyzyzg");
            //职业技能等级 高级工，技师，高级技师
            String zyzydj = bizObject.getString("zyzydj");
            //参评资格课程
            List<Map<String, Object>> cpzjzb = (List<Map<String, Object>>) bizObject.get("cpzjzb");
            //学习地图
            List<Map<String, Object>> xskcdt = (List<Map<String, Object>>) bizObject.get("xskcdt");
            List<Map<String, Object>> mskcdt = (List<Map<String, Object>>) bizObject.get("mskcdt");

            //执行审核
            Map<String, Object> result = reviewByConditions(sbjb, zyfzdj, zydj, zdsj, cjgzsj, zyzyzg, zyzydj, cpzjzb, xskcdt, mskcdt);
            Boolean jbzz = (Boolean) result.get("jbzz");
            Boolean cpkczz = (Boolean) result.get("cpkczz");
            Boolean dtqk = (Boolean) result.get("dtqk");
            Object jgms = result.get("jgms");

            //写回表单
            BizObjectCreatedModel biz = new BizObjectCreatedModel();
            biz.setId(objId);
            biz.setSchemaCode("jssb");
            if (jbzz) {
                biz.put("jbzz", "符合");
            } else {
                biz.put("jbzz", "不符合");
            }
            if (cpkczz) {
                biz.put("cpzgkc", "符合");
            } else {
                biz.put("cpzgkc", "不符合");
            }
            if (dtqk) {
                biz.put("xxdtwcqk", "符合");
            } else {
                biz.put("xxdtwcqk", "不符合");
            }
            if (jbzz && cpkczz && dtqk) {
                biz.put("shjg", "推荐");
            } else {
                biz.put("shjg", "不推荐");
            }
            biz.put("shyj", jgms);
            getBizObjectFacade().saveBizObject(getUserId(), biz, false);
        }
        return getOkResponseResult("审核完成");
    }

    /**
     * 执行审核
     *
     * @param sbjb
     * @param zyfzdj
     * @param zydj
     * @param zdsj
     * @param cjgzsj
     * @param zyzyzg
     * @param zyzydj
     * @param cpzjzb
     * @param xskcdt
     * @param mskcdt
     * @return
     */
    private Map<String, Object> reviewByConditions(String sbjb, String zyfzdj, String zydj,
                                                   String zdsj, Date cjgzsj, String zyzyzg, String zyzydj, List<Map<String, Object>> cpzjzb,
                                                   List<Map<String, Object>> xskcdt, List<Map<String, Object>> mskcdt) {
        //存放判断结果描述
        StringBuilder jgms = new StringBuilder();
        //职业评定等级
        List<String> zzpdtj = new ArrayList<>();
        //基本资质判定结果
        Boolean jbzz = true;
        //参评课程判定结果
        Boolean cpkczz = true;
        //学习地图判定了结果
        Boolean dtqk = true;
        //职业发展等级&&职业等级
        String substring = null;
        if (StringUtil.isEmpty(zyfzdj)) {
            substring = "99";
        } else {
            substring = zyfzdj.substring(1, zyfzdj.length());
        }


        //转换中断时间
        int i = 0;
        if (StringUtil.isNotEmpty(zdsj)) {
            i = Integer.parseInt(zdsj);
        }

        if ("初级讲师".equals(sbjb)) {
            if (StringUtil.isEmpty(zyfzdj) && StringUtil.isEmpty(zydj)) {
                jbzz = false;
                jgms.append("不符合职业发展等级或不符合职位层级;");
            }

            if (StringUtil.isEmpty(zyfzdj)) {
                jbzz = false;
                jgms.append("不符合职业发展等级或不符合职位层级;");
            } else {
                int a = Integer.parseInt(substring);
                //jbzz= a <= 15 && "普通员工".equals(zydj)?true:false;
                //需求变更  2022-5-6
                jbzz = a <= 15 ? true : false;
                if (!jbzz) {
                    jbzz = false;
                    jgms.append("不符合职业发展等级或不符合职位层级;");
                }
            }


            //工作年限
            if (cjgzsj == null) {
                jbzz = false;
                jgms.append("不符合工作年限门槛条件;");
            } else {
                int round = yearOfDifference(cjgzsj, i);
                if (round < 3) {
                    jbzz = false;
                    jgms.append("不合符工作年限门槛条件");
                }
            }


            //专业职业资格
            if (StringUtil.isEmpty(zyzyzg) && StringUtil.isEmpty(zyzydj)) {
                jbzz = false;
                jgms.append("不符合专业技术职务或不符合职业技能等级;");
            }
            if (StringUtil.isNotEmpty(zyzyzg) && !"无".equals(zyzyzg)) {
                zzpdtj = new ArrayList<>(Arrays.asList("初级", "中级", "副高", "高级"));
                boolean result = zzpdtj.contains(zyzyzg);
                if (!result) {
                    jbzz = false;
                    jgms.append("不符合专业技术职务;");
                }
            } else {
                zzpdtj = new ArrayList<>(Arrays.asList("高级工", "技师", "高级技师"));
                boolean result = zzpdtj.contains(zyzydj);
                if (!result) {
                    jbzz = false;
                    jgms.append("不符合职业技能等级;");
                }
            }

            //参评资格课程判断,初级不判断
//            if (CollectionUtils.isNotEmpty(cpzjzb)) {
//                List<String> pd = new ArrayList<>(Arrays.asList("合格"));
//                boolean result = cpzjzb.stream().filter(s -> pd.contains(s.get("kcdj"))).findAny().isPresent();
//                if (!result) {
//                    cpkczz = false;
//                    jgms.append("不符合参评资格课程门槛条件;");
//                }
//            } else {
//                cpkczz = false;
//                jgms.append("不符合参评资格课程门槛条件;");
//            }

            //学习地图判断，初级不用判断

        }


        if ("中级讲师".equals(sbjb)) {
            if (StringUtil.isEmpty(zyfzdj) && StringUtil.isEmpty(zydj)) {
                jbzz = false;
                jgms.append("不符合职业发展等级或不符合职位层级;");
            }

            if (StringUtil.isEmpty(zyfzdj)) {
                jbzz = false;
                jgms.append("不符合职业发展等级或不符合职位层级;");
            } else {
                int a = Integer.parseInt(substring);
                ////需求变更  2022-5-6
                jbzz = a <= 12 ? true : false;
                if (!jbzz) {
                    jbzz = false;
                    jgms.append("不符合职业发展等级或不符合职位层级;");
                }
            }

            //工作年限
            if (cjgzsj == null) {
                jbzz = false;
                jgms.append("不符合工作年限门槛条件;");
            } else {
                int round = yearOfDifference(cjgzsj, i);
                if (round < 5) {
                    jbzz = false;
                    jgms.append("不合符工作年限门槛条件");
                }
            }

            //专业职业资格
            if (StringUtil.isEmpty(zyzyzg) && StringUtil.isEmpty(zyzydj)) {
                jbzz = false;
                jgms.append("不符合专业技术职务或不符合职业技能等级;");
            }
            if (StringUtil.isNotEmpty(zyzyzg) && !"无".equals(zyzyzg)) {
                zzpdtj = new ArrayList<>(Arrays.asList("中级", "副高", "高级"));
                boolean result = zzpdtj.contains(zyzyzg);
                if (!result) {
                    jbzz = false;
                    jgms.append("不符合专业技术职务;");
                }
            } else {
                zzpdtj = new ArrayList<>(Arrays.asList("技师", "高级技师"));
                boolean result = zzpdtj.contains(zyzydj);
                if (!result) {
                    jbzz = false;
                    jgms.append("不符合职业技能等级;");
                }
            }

            //参评资格课程判断
            if (CollectionUtils.isNotEmpty(cpzjzb)) {
                List<String> pd = new ArrayList<>(Arrays.asList("优秀", "精品"));
                boolean result = cpzjzb.stream().filter(s -> pd.contains(s.get("kcdj"))).findAny().isPresent();
                if (!result) {
                    cpkczz = false;
                    jgms.append("不符合参评资格课程门槛条件;");
                }
            } else {
                cpkczz = false;
                jgms.append("不符合参评资格课程门槛条件;");
            }

            //学习地图判断
            if (CollectionUtils.isEmpty(xskcdt) || CollectionUtils.isEmpty(mskcdt)) {
                dtqk = false;
                jgms.append("学习地图课程未完成;");
            }
            List<Map<String, Object>> xscollect = xskcdt.stream().filter(s -> s.get("jsdj").equals("初级讲师")).collect(Collectors.toList());
            List<Map<String, Object>> mscollect = mskcdt.stream().filter(s -> s.get("jsdj").equals("初级讲师")).collect(Collectors.toList());
            boolean xskc = false;
            boolean mskc = false;
            if (CollectionUtils.isNotEmpty(xscollect)) {
                xskc = xscollect.stream().allMatch(s -> s.get("sfwc").equals("是") && s.get("jsdj").equals("初级讲师"));
            }
            if (CollectionUtils.isNotEmpty(mscollect)) {
                mskc = mscollect.stream().allMatch(s -> s.get("sfwc").equals("是") && s.get("jsdj").equals("初级讲师"));
            }
            if (xskc != true) {
                dtqk = false;
                jgms.append("学习地图线上课程未完成;");
            }
            if (mskc != true) {
                dtqk = false;
                jgms.append("学习地图面授课程未完成;");
            }
        }


        if ("高级讲师".equals(sbjb)) {
            if (StringUtil.isEmpty(zyfzdj) && StringUtil.isEmpty(zydj)) {
                jbzz = false;
                jgms.append("不符合职业发展等级或不符合职位层级;");
            }


            int a = Integer.parseInt(substring);
            jbzz = a <= 9 || (!"普通员工".equals(zydj) && !"主管".equals(zydj)) ? true : false;
            if (!jbzz) {
                jbzz = false;
                jgms.append("不符合职业发展等级或不符合职位层级;");
            }

            //工作年限
            if (cjgzsj == null) {
                jbzz = false;
                jgms.append("不符合工作年限门槛条件;");
            } else {
                int round = yearOfDifference(cjgzsj, i);
                if (round < 8) {
                    jbzz = false;
                    jgms.append("不合符工作年限门槛条件");
                }
            }

            //专业职业资格
            if (StringUtil.isEmpty(zyzyzg) && StringUtil.isEmpty(zyzydj)) {
                jbzz = false;
                jgms.append("不符合专业技术职务或不符合职业技能等级;");
            }
            if (StringUtil.isNotEmpty(zyzyzg) && !"无".equals(zyzyzg)) {
                zzpdtj = new ArrayList<>(Arrays.asList("中级", "副高", "高级"));
                boolean result = zzpdtj.contains(zyzyzg);
                if (!result) {
                    jbzz = false;
                    jgms.append("不符合专业技术职务;");
                }
            } else {
                zzpdtj = new ArrayList<>(Arrays.asList("技师", "高级技师"));
                boolean result = zzpdtj.contains(zyzydj);
                if (!result) {
                    jbzz = false;
                    jgms.append("不符合职业技能等级;");
                }
            }

            //参评资格课程判断
            if (CollectionUtils.isNotEmpty(cpzjzb)) {
                List<String> pd = new ArrayList<>(Arrays.asList("精品"));
                boolean result = cpzjzb.stream().filter(s -> pd.contains(s.get("kcdj"))).findAny().isPresent();
                if (!result) {
                    cpkczz = false;
                    jgms.append("不符合参评资格课程门槛条件;");
                }
            } else {
                cpkczz = false;
                jgms.append("不符合参评资格课程门槛条件;");
            }

            //学习地图判断
            if (CollectionUtils.isEmpty(xskcdt) || CollectionUtils.isEmpty(mskcdt)) {
                dtqk = false;
                jgms.append("学习地图课程未完成;");
            }
            List<Map<String, Object>> xscollect = xskcdt.stream().filter(s -> s.get("jsdj").equals("中级讲师")).collect(Collectors.toList());
            List<Map<String, Object>> mscollect = mskcdt.stream().filter(s -> s.get("jsdj").equals("中级讲师")).collect(Collectors.toList());
            boolean xskc = false;
            boolean mskc = false;
            if (CollectionUtils.isNotEmpty(xscollect)) {
                xskc = xscollect.stream().allMatch(s -> s.get("sfwc").equals("是") && s.get("jsdj").equals("中级讲师"));
            }
            if (CollectionUtils.isNotEmpty(mscollect)) {
                mskc = mscollect.stream().allMatch(s -> s.get("sfwc").equals("是") && s.get("jsdj").equals("中级讲师"));
            }
            if (xskc != true) {
                dtqk = false;
                jgms.append("学习地图线上课程未完成;");
            }
            if (mskc != true) {
                dtqk = false;
                jgms.append("学习地图面授课程未完成;");
            }
        }


        if ("资深讲师".equals(sbjb)) {
            if (StringUtil.isEmpty(zyfzdj) && StringUtil.isEmpty(zydj)) {
                jbzz = false;
                jgms.append("不符合职业发展等级或不符合职位层级;");
            }


            int a = Integer.parseInt(substring);
            jbzz = a <= 9 || (!"普通员工".equals(zydj) && !"主管".equals(zydj)) ? true : false;
            if (!jbzz) {
                jbzz = false;
                jgms.append("不符合职业发展等级或不符合职位层级;");
            }

            //工作年限
            if (cjgzsj == null) {
                jbzz = false;
                jgms.append("不符合工作年限门槛条件;");
            } else {
                int round = yearOfDifference(cjgzsj, i);
                if (round < 12) {
                    jbzz = false;
                    jgms.append("不合符工作年限门槛条件");
                }
            }

            //专业职业资格
            if (StringUtil.isEmpty(zyzyzg) && StringUtil.isEmpty(zyzydj)) {
                jbzz = false;
                jgms.append("不符合专业技术职务或不符合职业技能等级;");
            }
            if (StringUtil.isNotEmpty(zyzyzg) && !"无".equals(zyzyzg)) {
                zzpdtj = new ArrayList<>(Arrays.asList("副高", "高级"));
                boolean result = zzpdtj.contains(zyzyzg);
                if (!result) {
                    jbzz = false;
                    jgms.append("不符合专业技术职务");
                }
            } else {
                zzpdtj = new ArrayList<>(Arrays.asList("高级技师"));
                boolean result = zzpdtj.contains(zyzydj);
                if (!result) {
                    jbzz = false;
                    jgms.append("不符合职业技能等级;");
                }
            }

            //参评资格课程判断
            if (CollectionUtils.isNotEmpty(cpzjzb)) {
                List<String> pd = new ArrayList<>(Arrays.asList("精品"));
                boolean result = cpzjzb.stream().filter(s -> pd.contains(s.get("kcdj"))).findAny().isPresent();
                if (!result) {
                    cpkczz = false;
                    jgms.append("不符合参评资格课程门槛条件;");
                }
            } else {
                cpkczz = false;
                jgms.append("不符合参评资格课程门槛条件;");
            }

            //学习地图判断
            if (CollectionUtils.isEmpty(xskcdt) || CollectionUtils.isEmpty(mskcdt)) {
                dtqk = false;
                jgms.append("学习地图课程未完成;");
            }
            List<Map<String, Object>> xscollect = xskcdt.stream().filter(s -> s.get("jsdj").equals("高级讲师")).collect(Collectors.toList());
            List<Map<String, Object>> mscollect = mskcdt.stream().filter(s -> s.get("jsdj").equals("高级讲师")).collect(Collectors.toList());
            boolean xskc = false;
            boolean mskc = false;
            if (CollectionUtils.isNotEmpty(xscollect)) {
                xskc = xscollect.stream().allMatch(s -> s.get("sfwc").equals("是") && s.get("jsdj").equals("高级讲师"));
            }
            if (CollectionUtils.isNotEmpty(mscollect)) {
                mskc = mscollect.stream().allMatch(s -> s.get("sfwc").equals("是") && s.get("jsdj").equals("高级讲师"));
            }
            if (xskc != true) {
                dtqk = false;
                jgms.append("学习地图线上课程未完成;");
            }
            if (mskc != true) {
                dtqk = false;
                jgms.append("学习地图面授课程未完成;");
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("jbzz", jbzz);
        map.put("cpkczz", cpkczz);
        map.put("dtqk", dtqk);
        map.put("jgms", jgms);
        return map;
    }

//    /**
//     * 计算相差多少年   废弃
//     * @param cjgzsj
//     * @param i
//     * @return
//     */
//    private int yearOfDifference(Date cjgzsj,int i){
//        Date now = new Date();
//        SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
//
//        Calendar bef = Calendar.getInstance();
//        Calendar aft = Calendar.getInstance();
//        bef.setTime(now);
//        aft.setTime(cjgzsj);
//        int ksyear = bef.get(Calendar.YEAR);
//        int ksmonth = bef.get(Calendar.MONTH) + 1;
//        int ksday = bef.get(Calendar.DAY_OF_MONTH);
//
//        int jsyear = aft.get(Calendar.YEAR);
//        int jsmonth = aft.get(Calendar.MONTH) + 1;
//        int jsday = aft.get(Calendar.DAY_OF_MONTH);
//
//        //年差
//        int yearInterval = ksyear - jsyear;
//        //月差
//        if (ksmonth < jsmonth || ksmonth == jsmonth && ksday < jsday) {
//            yearInterval--;
//        }
//        int monthInterval = ksmonth - jsmonth;
//        if (ksday < jsday) {
//            monthInterval--;
//        }
//        monthInterval %= 12;
//        int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
//        Double b = new Double(monthsDiff - i);
//        //int round = (int) Math.round(b / 12);
//        //进位制
//        int round = (int) Math.ceil(b / 12);
//        return  round;
//    }

    /**
     * 计算相差多少年
     *
     * @param cjgzsj
     * @param i
     * @return
     */
    private int yearOfDifference(Date cjgzsj, int i) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        String format1 = simpleDateFormat.format(cjgzsj);
        String format2 = simpleDateFormat.format(now);
        Temporal temporal1 = LocalDate.parse(format1);
        Temporal temporal2 = LocalDate.parse(format2);
        //两个日期相差月
        int Months = (int) ChronoUnit.MONTHS.between(temporal1, temporal2);
        Double b = new Double(Months - i);
        int round = (int) Math.ceil(b / 12);
        return round;
    }

    /**
     * 驳回
     */
    @PostMapping("/reject")
    public ResponseResult reject(@RequestBody List<Map<String, Object>> map) {
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        for (Map m : map) {
            String objId = (String) m.get("objId");
            String code = (String) m.get("code");
            BizObjectCreatedModel biz = new BizObjectCreatedModel("jssb", new HashMap<>(), false);
            biz.setId(objId);
            if ("jcshtj".equals(code)) {
                biz.put("dqjd", "申请人");
                biz.put("zt", "驳回，待重新提交");
                biz.put("fbzt", "已驳回");
            }
            if ("jsjgfb".equals(code)) {
                biz.put("dqjd", "讲师_基层审核推荐");
                biz.put("fbzt", "驳回，待重新提交");
                biz.put("fbzt", "已驳回");
            }

            getBizObjectFacade().saveBizObject(getUserId(), biz, false);

        }
        return getOkResponseResult("驳回成功");
    }

    /**
     * 提交审批
     * @param dqyw
     * @param kcsbId
     * @return
     */
//    @GetMapping("/businessLine")
//    @Transactional
//    public ResponseResult businessLine(@RequestParam(required = false) String dqyw, @RequestParam String kcsbId) {
//
//        String userId = getUserId();
//        UserModel user = getOrganizationFacade().getUser(userId);
//        String[] splitID = kcsbId.split(";");
//        String kcsbNewTableName = getBizObjectFacade().getTableName("jssb");
//        Map<String, Object> fMap = new HashMap<>();
//        String hdmc = null;
//        // 处理传入的id拼接数据
//        for (int j = 0; j < splitID.length; j++) {
//            StringBuilder sql = new StringBuilder();
//            sql.append("SELECT sequenceStatus,createdTime  FROM `iwrwy_jsndsp` where bdid ='").append(splitID[j]).append("'").append(" ORDER BY createdTime desc LIMIT 0,1");
//            List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
//                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//            if (CollectionUtils.isNotEmpty(sqllist)){
//                String sequenceStatus = (String) sqllist.get(0).get("sequenceStatus");
//                if (!"COMPLETED".equals(sequenceStatus)) {
//                    return getErrResponseResult(500L, "审批未结束，请勿重复提交");
//                }
//            }
//            StringBuilder  sqls=new StringBuilder();
//            String jsndspTableName = getBizObjectFacade().getTableName("jsndsp");
//            sqls.append("select * from ").append(jsndspTableName).append(" where bdid='").append(splitID[j]).append("' and sequenceStatus='PROCESSING'");
//            List<Map<String, Object>> sqlsresult = entityManager.createNativeQuery(sqls.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//            if (CollectionUtils.isNotEmpty(sqlsresult)){
//                return  getErrResponseResult(-1L,"流程审批中，请勿重复发起");
//            }
//
//            StringBuilder selectCourseInfoSql = new StringBuilder();
//            selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
//            // 根据ID取得讲师申报信息
//            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//            String spzt =(String) resultList.get(0).get("spzt");
//            if ("通过".equals(spzt)){
//                return getErrResponseResult(-1L,"审批已通过，请勿重复发起");
//            }
//            // 若当前节点为审批相关，则发起对应审批流程
//            if ("jcshtj".equals(dqyw)) {
//                // 活动ID
//                String pphdId = (String) resultList.get(0).get("hdmc");
//                StringBuilder getHdmcByIdSql = new StringBuilder();
//                String pphdTableName = getBizObjectFacade().getTableName("pphd");
//                getHdmcByIdSql.append("SELECT * FROM `" + pphdTableName + "` T WHERE T.id = '" + pphdId + "'");
//                List<Map<String, Object>> hdmcList = entityManager.createNativeQuery(getHdmcByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//                String hdmcId = (String) hdmcList.get(0).get("id");
//                hdmc = (String) hdmcList.get(0).get("hdmc");
//                // 获取发起活动的部门
//                DepartmentModel dept = getOrganizationFacade().getDepartment((String) hdmcList.get(0).get("ownerDeptId"));
//                //讲师申报表单id
//                String jssbid = (String) resultList.get(0).get("id");
//                String creater = (String) resultList.get(0).get("creater");
//                Object createdTime = resultList.get(0).get("createdTime");
//                String sqr = getBizObjectFacade().getBizObject("jssb", jssbid).getCreater().getName();
//                SelectionValue selectionValue = new SelectionValue();
//                selectionValue.setId(creater);
//                selectionValue.setType(UnitType.USER);
//                //创建流程信息
//                fMap.put("mc", hdmc + "_" + sqr + dept.getName());
//                fMap.put("fqr", Collections.singletonList(selectionValue));
//                fMap.put("fazz", null);
//                fMap.put("fqsj", createdTime);
//                fMap.put("bdid", splitID[j]);
//                fMap.put("hdmc", hdmc);
//                List<Map<String, Object>> zb = new ArrayList<>();
//                Map<String, Object> map = new HashMap<>();
//                BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("jssb", splitID[j]);
//
//                //工号
//                map.put("jssb", bizObject.getId());
//                map.put("xm", bizObject.get("xm"));
//                map.put("dw", bizObject.get("dw"));
//                map.put("bm", bizObject.get("bm"));
//                map.put("zw", bizObject.get("zw"));
//                map.put("zyzyzg", bizObject.get("zyzyzg"));
//                map.put("zyfzdj", bizObject.get("zyfzdj"));
//                map.put("cjgzsj", bizObject.get("cjgzsj"));
//                map.put("shjg",bizObject.get("shjg"));
//                map.put("shyj",bizObject.get("shyj"));
//                map.put("rowStatus", "Added");
//                zb.add(map);
//                fMap.put("jssbxxb", zb);
//            }
//        // 发起基层领导审批流程
//        BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("jsndsp", fMap, false);
//        String bizObjectId = getBizObjectFacade().saveBizObject(userId, departmentLeaderApproval, false);
//        String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "jsndspProcess", bizObjectId, true);
//        StringBuilder upsql = new StringBuilder();
//        upsql.append("update iwrwy_jsndsp set name='基层评审推荐审批_").append(hdmc).append("' where id='").append(bizObjectId).append("'");
//
//        log.info("\n=======基层领导审批流程发起成功,instanceId={}", instanceId);
//        upsql.setLength(0);
//        upsql.append("update iwrwy_jssb set spzt='已提交审批' where id='").append(splitID[j]).append("'");
//        entityManager.createNativeQuery(upsql.toString()).executeUpdate();
//        }
//        return getOkResponseResult("success");
//    }

    /**
     * 提交审批
     *
     * @param dqyw
     * @param kcsbId
     * @return
     */
    @GetMapping("/businessLine")
    @Transactional
    public ResponseResult newbusinessLine(@RequestParam(required = false) String dqyw, @RequestParam String kcsbId) {

        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(userId);
        String[] splitID = kcsbId.split(";");
        String kcsbNewTableName = getBizObjectFacade().getTableName("jssb");
        Map<String, Object> fMap = new HashMap<>();
        List<Map<String, Object>> zb = new ArrayList<>();
        String hdmc = null;
        // 处理传入的id拼接数据
        for (int j = 0; j < splitID.length; j++) {
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT a.sequenceStatus,a.createdTime  FROM iwrwy_jsndsp a left join  iwrwy_jssbxxb b  on  a.id=b.parentId  where b.jssb='").append(splitID[j]).append("'").append(" ORDER BY createdTime desc LIMIT 0,1");
            List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (CollectionUtils.isNotEmpty(sqllist)) {
                String sequenceStatus = (String) sqllist.get(0).get("sequenceStatus");
                if ("PROCESSING".equals(sequenceStatus)) {
                    return getErrResponseResult(500L, "流程审批中，请勿重复发起");
                }
            }

            StringBuilder selectCourseInfoSql = new StringBuilder();
            selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
            // 根据ID取得讲师申报信息
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            String spzt = (String) resultList.get(0).get("spzt");
            if ("通过".equals(spzt)) {
                return getErrResponseResult(-1L, "审批已通过，请勿重复发起");
            }
            // 若当前节点为审批相关，则发起对应审批流程
            if ("jcshtj".equals(dqyw)) {
                // 活动ID
                String pphdId = (String) resultList.get(0).get("hdmc");
                StringBuilder getHdmcByIdSql = new StringBuilder();
                String pphdTableName = getBizObjectFacade().getTableName("pphd");
                getHdmcByIdSql.append("SELECT * FROM `" + pphdTableName + "` T WHERE T.id = '" + pphdId + "'");
                List<Map<String, Object>> hdmcList = entityManager.createNativeQuery(getHdmcByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                String hdmcId = (String) hdmcList.get(0).get("id");
                hdmc = (String) hdmcList.get(0).get("hdmc");
                // 获取发起活动的部门
                DepartmentModel dept = getOrganizationFacade().getDepartment((String) hdmcList.get(0).get("ownerDeptId"));
                //讲师申报表单id
                String jssbid = (String) resultList.get(0).get("id");
                String creater = (String) resultList.get(0).get("creater");
                Object createdTime = resultList.get(0).get("createdTime");
                String sqr = getBizObjectFacade().getBizObject("jssb", jssbid).getCreater().getName();
                SelectionValue selectionValue = new SelectionValue();
                selectionValue.setId(userId);
                selectionValue.setType(UnitType.USER);
                //创建流程信息
                fMap.put("mc", hdmc + "_" + user.getName() + dept.getName());
                fMap.put("fqr", Collections.singletonList(selectionValue));
                SelectionValue fqzz = new SelectionValue();
                fqzz.setId(dept.getId());
                fqzz.setType(UnitType.DEPARTMENT);
                fMap.put("fqzz", Collections.singletonList(fqzz));
                fMap.put("fqsj", createdTime);
                fMap.put("hdmc", hdmc);

                Map<String, Object> map = new HashMap<>();
                BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("jssb", splitID[j]);

                //工号
                map.put("jssb", bizObject.getId());
                map.put("xm", bizObject.get("xm"));
                map.put("dw", bizObject.get("dw"));
                map.put("bm", bizObject.get("bm"));
                map.put("zw", bizObject.get("zw"));
                map.put("zyzyzg", bizObject.get("zyzyzg"));
                map.put("zyfzdj", bizObject.get("zyfzdj"));
                map.put("cjgzsj", bizObject.get("cjgzsj"));
                map.put("shjg", bizObject.get("shjg"));
                map.put("shyj", bizObject.get("shyj"));
                map.put("sbjb", bizObject.get("sbjb"));
                map.put("xrjsjb", bizObject.get("xrjsjb"));
                map.put("xrjbprsj", bizObject.get("xrjbprsj"));
                map.put("rowStatus", "Added");
                zb.add(map);

            }
        }
        fMap.put("jssbxxb", zb);
        fMap.put("shjg", "通过");
        // 发起基层领导审批流程
        BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("jsndsp", fMap, false);
        String bizObjectId = getBizObjectFacade().saveBizObject(userId, departmentLeaderApproval, false);
        String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "jsndspProcess", bizObjectId, true);
        StringBuilder upsql = new StringBuilder();
        upsql.append("update iwrwy_jsndsp set name='基层评审推荐审批_").append(hdmc).append("' where id='").append(bizObjectId).append("'");

        log.info("\n=======基层领导审批流程发起成功,instanceId={}", instanceId);
        for (int i = 0; i < splitID.length; i++) {
            upsql.setLength(0);
            upsql.append("update iwrwy_jssb set spzt='已提交' where id='").append(splitID[i]).append("'");
            entityManager.createNativeQuery(upsql.toString()).executeUpdate();
        }

        return getOkResponseResult("success");
    }

    /**
     * 发布审核结果  基层----结果发布
     */
    @PostMapping("/releaseAuditResults")
    @Transactional
    public ResponseResult releaseAuditResults(@RequestBody List<Map<String, Object>> map) {
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        for (Map m : map) {
            String objId = (String) m.get("objId");
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT a.sequenceStatus,a.createdTime  FROM iwrwy_jsndsp a left join  iwrwy_jssbxxb b  on  a.id=b.parentId  where b.jssb='").append(objId).append("'").append(" ORDER BY createdTime desc LIMIT 0,1");
            List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (CollectionUtils.isEmpty(sqllist)) {
                return getErrResponseResult(500L, "未提交领导审批，不允许发布");
            }
            String sequenceStatus = (String) sqllist.get(0).get("sequenceStatus");
            if (!"COMPLETED".equals(sequenceStatus)) {
                return getErrResponseResult(500L, "审批未结束，不允许发布");
            }
            //修改业务节点到学院评聘结果发布
            //只有审核结果为推荐的才到学院评聘结果与发布
            StringBuilder selectSql = new StringBuilder();
            selectSql.append("select shjg from iwrwy_jssb where  id='").append(objId).append("'");
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectSql.toString()).unwrap(NativeQueryImpl.class)
                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            String shjg = (String) resultList.get(0).get("shjg");
            StringBuilder updateDQYWsql = new StringBuilder();
            if ("推荐".equals(shjg)) {
                updateDQYWsql.append("UPDATE iwrwy_jssb T set T.dqjd = '讲师_学院评聘及结果发布',T.spzt='已发布',T.zt='基层推荐',T.jgfbCode='jsjgfb' WHERE T.id = '" + objId + "'");
                int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
            } else {
                updateDQYWsql.append("UPDATE iwrwy_jssb T set T.zt='基层不推荐',T.spzt='已发布' WHERE T.id = '" + objId + "'");
                int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
            }

        }
        return getOkResponseResult("发布成功");
    }

    /**
     * 发布入库   学院评聘--讲师库管理
     */
    @PostMapping("/warehousing")
    @Transactional
    public ResponseResult warehousing(@RequestBody List<Map<String, Object>> map) {
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        for (Map m : map) {
            String objId = (String) m.get("objId");
            StringBuilder sql = new StringBuilder();
            sql.append("select  * from iwrwy_jssb where id='").append(objId).append("'");
            List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            Map<String, Object> objectMap = sqllist.get(0);
            String shjg = (String) objectMap.get("shjg");
            String gh = (String) objectMap.get("gh");
            //判断是否已经发布过
            StringBuilder newSql = new StringBuilder();
            newSql.append("SELECT * FROM `iwrwy_jskgl` where gh='").append(gh).append("' ORDER BY createdTime desc LIMIT 0,1");
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(newSql.toString()).unwrap(NativeQueryImpl.class)
                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (CollectionUtils.isNotEmpty(resultList)) {
                newSql.setLength(0);
                newSql.append("update iwrwy_jskgl set przt='考核解聘' where id='").append(resultList.get(0).get("id")).append("'");
                entityManager.createNativeQuery(newSql.toString()).executeUpdate();
            }
            if ("推荐".equals(shjg)) {
                BizObjectCreatedModel biz = new BizObjectCreatedModel();
                biz.setSchemaCode("jskgl");

                SelectionValue selectionValue = new SelectionValue();
                selectionValue.setId((String) objectMap.get("creater"));
                selectionValue.setType(UnitType.USER);

                biz.put("xm", Collections.singletonList(selectionValue));
                biz.put("gh", objectMap.get("gh"));
                biz.put("dw", objectMap.get("dw"));
                biz.put("bm", objectMap.get("bm"));
                biz.put("zw", objectMap.get("zw"));
                biz.put("cjgzsj", objectMap.get("cjgzsj"));
                biz.put("jsdj", objectMap.get("sbjb"));
                biz.put("przt", "聘任");
                biz.put("prsj", new Date());
//                getBizObjectFacade().saveBizObject(getUserId(), biz, false);
                getBizObjectFacade().saveBizObject((String) objectMap.get("creater"), biz, false);
                StringBuilder updatesql = new StringBuilder();
                updatesql.append("update iwrwy_jssb set xyjgfb='已发布' where id='").append(objId).append("'");
                entityManager.createNativeQuery(updatesql.toString()).executeUpdate();
            } else {
                return getErrResponseResult(500L, "不符合审核结果，不允许提交");
            }

        }
        return getOkResponseResult("发布成功");
    }

    /**
     * 获取学习地图数据
     */
    @GetMapping("/getstudymap")
    public ResponseResult getStudyMap(String gh) {
        Map<String, Object> result = new HashMap<>();
        //线上课程
        String xskcTableName = getBizObjectFacade().getTableName("xskc");

        StringBuilder sql = new StringBuilder();
        sql.append("select kczt,sfwc,jsdj from " + xskcTableName + " where xygh='").append(gh).append("'");
        List<Map<String, Object>> xskclist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        result.put("xskc", xskclist);
        //面授课程
        StringBuilder sql1 = new StringBuilder();
        sql1.append("select zt,sfwc,jsdj from iwrwy_mskcb where xygh='").append(gh).append("'");
        List<Map<String, Object>> mskclist = entityManager.createNativeQuery(sql1.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        result.put("mskc", mskclist);
        return getOkResponseResult(result, "返回数据成功");
    }

    /**
     * 获取参评资格课程
     */
    @GetMapping("/getQualificationCourses")
    public ResponseResult getQualificationCourses(String userId) {

        StringBuilder sql = new StringBuilder();
        //课程编码   课程名称  课程分类 课时 课程类别 年度 评审级别  开放范围
        //2021以前取面授+图文+主开发人是自己
        sql.append("select id,kcbh,courseName,modality,classHour,category,year,psjb,kkffw from iwrwy_kcqd " +
                "where modality in ('面授课程','图文课程') and kczt='已启用' and year < '2021-01-01' and kczkfr like '%").append(userId).append("%' ORDER BY year desc");
        List<Map<String, Object>> beforlist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isNotEmpty(beforlist)) {
            for (Map m : beforlist) {
                m.put("sfzkfr", "是");
            }
        }
        //不为主开发人
        //5-9 取消
//        sql.setLength(0);
//        sql.append("select id,kcbh,courseName,modality,classHour,category,year,psjb,kkffw from iwrwy_kcqd " +
//                "where modality in ('面授课程','图文课程') and hdzt='启用' and year < '2021-01-01' and tdcy like '%").append(userId).append("%' ORDER BY year desc");
//        List<Map<String, Object>> beforlistfzkfr = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
//                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//        if (CollectionUtils.isNotEmpty(beforlistfzkfr)) {
//            for (Map m : beforlistfzkfr) {
//                m.put("sfzkfr", "否");
//            }
//        }
        //2021之后只取面授
        StringBuilder sql2 = new StringBuilder();
        sql2.append("select id,kcbh,courseName,modality,classHour,category,year,psjb,kkffw from iwrwy_kcqd " +
                "where modality ='面授课程' and kczt='已启用' and year >= '2021-01-01' and kczkfr like '%").append(userId).append("%' ORDER BY year desc");
        List<Map<String, Object>> afterlist = entityManager.createNativeQuery(sql2.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isNotEmpty(afterlist)) {
            for (Map m : afterlist) {
                m.put("sfzkfr", "是");
            }
        }
        //不为主开发人
        //5-9取消
//        sql2.setLength(0);
//        sql2.append("select id,kcbh,courseName,modality,classHour,category,year,psjb,kkffw from iwrwy_kcqd " +
//                "where modality ='面授课程' and year >= '2021-01-01' and tdcy like '%").append(userId).append("%' ORDER BY year desc");
//        List<Map<String, Object>> afterlistfzkfr = entityManager.createNativeQuery(sql2.toString()).unwrap(NativeQueryImpl.class)
//                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//        if (CollectionUtils.isNotEmpty(afterlistfzkfr)){
//            for (Map m: afterlistfzkfr) {
//                m.put("sfzkfr","否");
//            }
//        }

        afterlist.addAll(beforlist);
        //afterlist.addAll(beforlistfzkfr);
        //afterlist.addAll(afterlistfzkfr);
        List<Map<String, Object>> mapList = afterlist;
        if (afterlist.size() > 10) {
            mapList = afterlist.subList(0, 10);
        }
        return getOkResponseResult(mapList, "获取数据成功");
    }

    /**
     * 批量下载课程文件
     */
    @PostMapping("/batchDownloadCourseFile")
    public ResponseResult batchDownloadCourseFile(@RequestBody List<String> bizIdList) {


        if (CollectionUtils.isEmpty(bizIdList)) {
            return getErrResponseResult(-1L, "请求参数不能为空");
        }

        if (bizIdList.size() > 200) {
            return getErrResponseResult(-2L, "导出文件过大,不要超过100条,请分批导出");
        }

        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("kcqd");
        queryModel.setQueryCode("kcqd");
        queryModel.setFilterExpr(Q.it("id", FilterExpression.Op.In, bizIdList));
        queryModel.setPageable(new PageableImpl(0, 200));
        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);
        if (page.getTotal() == 0) {
            return getErrResponseResult(-1L, "示例文件不存在");
        }
        //获取课程附件原数据
        Map<String, Map<String, Map<String, String>>> courseFile = page.getContent().stream().collect(Collectors.toMap(biz -> biz.getString("courseName"),
                biz -> getCourseAttachment(biz), (k1, k2) -> k1));


        //编写sh脚本
        String zip = executeZip(courseFile);

        if (zip == null) {
            return getErrResponseResult(-1l, "失败");
        }

        BizObjectCreatedModel batchdownload = new BizObjectCreatedModel("batchdownload", new HashMap<>(), false);
        batchdownload.put("course", courseFile.keySet().stream().collect(Collectors.joining(";")));
        batchdownload.put("downloadPath", zip);
        getBizObjectFacade().saveBizObject(getUserId(), batchdownload, false);

        return getOkResponseResult(zip);

    }

    public Map<String, Map<String, String>> getCourseAttachment(BizObjectModel biz) {
        Map<String, Map<String, String>> kcFileInfo = new HashMap<>(4);
//        //课程封面
//        List<Map<String,Object>> kcfm = (List<Map<String, Object>>) biz.get("kcfm");
        //课件（附件）
        List<Map<String, Object>> sjfj = (List<Map<String, Object>>) biz.get("sjfj");
        //讲师手册
        List<Map<String, Object>> jssc = (List<Map<String, Object>>) biz.get("jssc");

//        if (CollectionUtils.isNotEmpty(kcfm)) {
//            Map<String, String> kcfmFile = kcfm.stream().collect(Collectors.toMap(m -> String.valueOf(m.get("refId")),
//                    m -> String.valueOf(m.get("name")), (k1, k2) -> k1));
//            kcFileInfo.put("课程封面",kcfmFile);
//        }

        if (CollectionUtils.isNotEmpty(sjfj)) {
            Map<String, String> sjfjFile = sjfj.stream().collect(Collectors.toMap(m -> String.valueOf(m.get("refId")),
                    m -> String.valueOf(m.get("name")), (k1, k2) -> k1));
            kcFileInfo.put("课件", sjfjFile);
        }

        if (CollectionUtils.isNotEmpty(jssc)) {
            Map<String, String> jsscFile = jssc.stream().collect(Collectors.toMap(m -> String.valueOf(m.get("refId")),
                    m -> String.valueOf(m.get("name")), (k1, k2) -> k1));
            kcFileInfo.put("讲师手册", jsscFile);
        }


        return kcFileInfo;
    }

    public String executeZip(Map<String, Map<String, Map<String, String>>> courseFileInfo) {
        //创建文件目录
        String sourcePath = "/data/sftp/";
        String basePath = "/data/cloudpivot/courseFile/";
        String filePath = "课程附件".concat(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
        String currentPath = basePath + filePath;
        String zipFile = filePath.concat(".zip");

        StringBuilder command = new StringBuilder("mkdir -p ").append(currentPath);
        List<String> commandList = new ArrayList<>();

        commandList.add(command.toString());


        courseFileInfo.entrySet().forEach(kcEntry -> {
            StringBuilder kcPath = new StringBuilder(currentPath).append("/").append(kcEntry.getKey());

            commandList.add("mkdir ".concat(kcPath.toString()));

            kcEntry.getValue().entrySet().forEach(fileInfo -> {
                StringBuilder kcFilePath = new StringBuilder(kcPath).append("/").append(fileInfo.getKey());
                commandList.add("mkdir ".concat(kcFilePath.toString()));

                fileInfo.getValue().entrySet().forEach(fileMap -> {
                    commandList.add(new StringBuilder("mv ").append(sourcePath).append(fileMap.getKey()).append(fileMap.getValue()).append(" ")
                            .append(kcFilePath).append("/").append(fileMap.getValue()).toString());
                });
            });
        });

        //压缩
        commandList.add("cd ".concat(basePath));
        commandList.add("zip -q -r  ".concat(zipFile).concat(" ").concat(filePath));

        List<String> list = executeFlow(commandList);

        if (list == null) {
            return null;
        }

        log.info("执行脚本后返回结果:{}", JSON.toJSONString(list));

        log.info("压缩文件:{}", zipFile);

        return "/courseFile/".concat(zipFile);


    }

    public List<String> executeFlow(List<String> commands) {
        log.info("=========准备执行脚本:{}", JSON.toJSONString(commands));
        List<String> rspList = new ArrayList<String>();
        Runtime run = Runtime.getRuntime();
        try {
            Process proc = run.exec("/bin/bash", null, null);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            for (String line : commands) {
                out.println(line);
            }
            out.println("exit");//这个命令必须执行，否则in流不结束。
            String rspLine = "";
            while ((rspLine = in.readLine()) != null) {
                log.info("=============java 调用 bash 返回结果:{}", rspLine);
                rspList.add(rspLine);
            }
            proc.waitFor();
            in.close();
            out.close();
            proc.destroy();
        } catch (IOException e1) {
            log.info("=============java 调用 bash 失败1");
            e1.printStackTrace();
            return null;
        } catch (InterruptedException e) {
            log.info("=============java 调用 bash 失败2");
            e.printStackTrace();
            return null;
        }
        return rspList;
    }

    /**
     * 领导审批回写意见和状态
     */
    @GetMapping("/putCommentsAndStatus")
    public void putCommentsAndStatus(String bizId) {
        WorkflowInstanceModel instance = getWorkflowInstanceFacade().getByObjectId(bizId);

        if (instance == null || instance.getId() == null) {
            log.info("流程不存在,表单id={}", bizId);
            return;
        }

        WorkflowInstanceOptions workflowInstanceOptions = WorkflowInstanceOptions.builder().setWorkflowInstanceId(instance.getId()).setQueryCirculate(true).setDubboConfigService(this.getDubboConfigService()).build();
        List<BizCommentModel> bizComments = workflowInstanceOptions.getBizComments();
        Map<String, Object> loginfo = new HashMap<>();
        //审批节点名称 审批时间 操作 审批意见
        bizComments.forEach(t -> {
            ActionType actionType = t.getActionType();
            if (actionType == ActionType.APPROVAL ||
                    actionType == ActionType.ASSIST ||
                    actionType == ActionType.ADD_WORKITEM ||
                    actionType == ActionType.FORWARD) {

                if ("同意".equals(t.getResult().getName())) {
                    loginfo.put("spzt", "通过");
                    loginfo.put("spyj", t.getContent());
                } else {
                    loginfo.put("spzt", "驳回");
                    loginfo.put("spyj", t.getContent());
                }
            }
        });
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("jsndsp", bizId);


        List<Map<String, Object>> bTableSheets = (List<Map<String, Object>>) bizObject.get("jssbxxb");
        for (Map m : bTableSheets) {
            Map<String, Object> result = (Map<String, Object>) m.get("jssb");
            String id = (String) result.get("id");
            BizObjectCreatedModel biz = new BizObjectCreatedModel();
            biz.setId(id);
            biz.setSchemaCode("jssb");
            biz.put("spzt", bizObject.get("shjg"));
            biz.put("spyj", loginfo.get("spyj"));
            getBizObjectFacade().saveBizObject(instance.getOriginator(), biz, false);
        }


    }

    /**
     * 根据活动级别获取活动业务路线
     *
     * @param hdjb
     * @return
     */
    @GetMapping("/businessLine2")
    @Transactional
    public ResponseResult<String> businessLine2(@RequestParam String hdjb,
                                                @RequestParam(required = false) String kcsbId,
                                                @RequestParam(required = false) String fallBack) {

        // 业务路线
        String ywlx = "Undefined";

        StringBuilder sql = new StringBuilder();
        sql.append("select ywlx from iwrwy_ywxlNew where xlmc='").append(hdjb).append("'");
        ywlx = (String) entityManager.createNativeQuery(sql.toString()).getSingleResult();

        sql.setLength(0);
        sql.append("update iwrwy_jssb set jcpsCode ='jcshtj' where id='").append(kcsbId).append("'");
        entityManager.createNativeQuery(sql.toString()).executeUpdate();

        return getOkResponseResult(ywlx, "success");
    }

    /**
     * 讲师库管理发布
     */
    @PostMapping("/release")
    @Transactional
    public ResponseResult managementRelease(@RequestBody List<String> list) {
        if (CollectionUtils.isEmpty(list)) {
            return getErrResponseResult(-1L, "参数为空");
        }
        StringBuilder sql = new StringBuilder();
        for (String s : list) {
            sql.setLength(0);
            sql.append("update iwrwy_jskgl set xzfbzt='已发布' where id='").append(s).append("'");
            entityManager.createNativeQuery(sql.toString()).executeUpdate();
        }
        return getOkResponseResult("发布成功");
    }

    /**
     * 获取级别标准文件
     */
    @GetMapping("/getLevelStandardFile")
    public ResponseResult getLevelStandardFile(@RequestParam String code) {
        if (StringUtil.isEmpty(code)) {
            return getErrResponseResult(-1L, "参数为空");
        }
        BizObjectQueryModel query = new BizObjectQueryModel();
        query.setSchemaCode("examplesFile");
        query.setQueryCode("examplesFile");
        query.setPageable(new PageableImpl(0, 30));
        query.setFilterExpr(Q.it("exampleCode", FilterExpression.Op.Eq, code));
        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(query);
        Map<String, Object> map = new HashMap<>();
        if (page.getTotal() > 0) {
            BizObjectModel bizObjectModel = page.getContent().get(0);
            String id = bizObjectModel.getId();
            StringBuilder sql = new StringBuilder();
            String refId = null;
            sql.append("SELECT refId FROM `h_biz_attachment`  where bizObjectId='").append(id).append("'");
            refId = (String) entityManager.createNativeQuery(sql.toString()).getSingleResult();
            AttachmentModel attachmentByRefId = getBizObjectFacade().getAttachmentByRefId(refId);
            map.put("refId", refId);
            map.put("Ftype", attachmentByRefId.getMimeType());
        }
        return getOkResponseResult(map, "success");
    }
}
